const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

function showModal(title,content){
    wx.showModal({
        title: title,
        content: content,
        showCancel:false,
        success (res) {
        }
    })
    return
}

//正则验证
function validation (data,type) {
    let str = ''
    if(type == 'phone')
    {
      str = /^1\d{10}$/
    }
    else if(type == 'idcard')
    {
      str = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
    }
    else if(type == 'name')
    {
      str = /^[\u4E00-\u9FA5A-Za-z]+$/
    }
    else if(type == 'number')
    {
      // 验证非负浮点数
      str = /^(\-|\+)?\d+(\.\d+)?$/
    }
    else if(type == 'alphanumeric')
    {
      // 验证由数字和26个英文字母组成的字符串
      str = /^[A-Za-z0-9]+$/
    }
    if (str.test(data)) {
      return true
    }
    else{
      return false
    }
}

function showToast(title,icon,duration){
    wx.showToast({
      title: title,
      icon: icon,
      duration: duration,
    })
}

//判断是否是表情
function isEmojiCharacter(substring) {
    for (var i = 0; i < substring.length; i++) {
      var hs = substring.charCodeAt(i);
      if (0xd800 <= hs && hs <= 0xdbff) {
        if (substring.length > 1) {
          var ls = substring.charCodeAt(i + 1);
          var uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
          if (0x1d000 <= uc && uc <= 0x1f77f) {
            return true;
          }
          }
      } else if (substring.length > 1) {
        var ls = substring.charCodeAt(i + 1);
        if (ls == 0x20e3) {
          return true;
        }
      } else {
        if (0x2100 <= hs && hs <= 0x27ff) {
          return true;
        } else if (0x2B05 <= hs && hs <= 0x2b07) {
          return true;
        } else if (0x2934 <= hs && hs <= 0x2935) {
          return true;
        } else if (0x3297 <= hs && hs <= 0x3299) {
          return true;
        } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
          return true;
        }
      }
    }
}

function setNavBarColor(fontColor,bgColor){
  wx.setNavigationBarColor({
    frontColor:fontColor,
    backgroundColor:bgColor
  })
}
function setNavBarTitle(title){
  wx.setNavigationBarTitle({
    title:title
  })
}

// 时间格式化输出，如11:03 25:19 每1s都会调用一次
function dateformat(micro_second,t = 1) {
  // 总秒数
  var second = Math.floor(micro_second / 1000);
  // 天数
  var day = Math.floor(second / 3600 / 24);
  // 小时
  var hr = formatNumber(Math.floor(second / 3600));
  // 分钟
  var min = formatNumber(Math.floor(second / 60 % 60));
  // 秒
  var sec = formatNumber(Math.floor(second % 60));
  if (t == 0) {
    return day + "天" + hr + "小时" + min + "分钟" + sec + "秒";
  }else{
    return  hr + min + sec;
  }
}

function getAjax(url,callback,data,failback){
  wx.request({
    url:url,
    data:data,
    method:'get',
    success(res){
      callback(res)
    },
    fail(err){
      failback(err)
    }
  })
}
function postAjax(url,callback,data,failback){
  wx.request({
    url:url,
    data:data,
    header:{
      'content-type': 'application/x-www-form-urlencoded'
    },
    success(res){
      callback(res)
    },
    fail(err){
      failback(err)
    }
  })
}

function showModelAll(title,content,callback,cancelback){
    wx.showModal({
        title: title,
        content: content,
        success(res) {
            if (res.confirm) {
                callback()
            } else if (res.cancel) {
                cancelback()
            }
        }
    })
}

//转换时间格式 （年月日）
function setTime(timestr){
  var date = new Date(timestr);
  var Y = date.getFullYear();
  var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1);
  var D = change(date.getDate());
  var h = change(date.getHours());
  var minute = date.getMinutes();
  var second = date.getSeconds();
  minute = minute < 10 ? ('0' + minute) : minute;
  second = second < 10 ? ('0' + second) : second;
  return Y + '-' + M + '-' + D;
}

//转换时间格式 （年月日）
function setTime2(timestr){
  var date = new Date(timestr * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
  var Y = date.getFullYear();
  var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
  var D = change(date.getDate());
  var h = change(date.getHours());
  var m = change(date.getMinutes());
  var s = change(date.getSeconds());
  return Y + '-' + M + '-' + D+ ' ' + h + ':' + m + ':' + s;
}

//转换时间格式 （日）
function setTime3(str){
  str = str.replace(/[^\d]/g,'/');
  str= (str.substring(str.length-1) == '/')? str.substring(0,str.length-1) : str ;
  var date = new Date(str);
  var Y = date.getFullYear();
  var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1);
  var D = change(date.getDate())
  return M +'.' + D
}

//转换时间格式 （年月日）
function setTime4(timestr){
  var date = new Date(timestr);
  var Y = date.getFullYear();
  var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1);
  var D = change(date.getDate());
  var h = change(date.getHours());
  var minute = date.getMinutes();
  var second = date.getSeconds();
  minute = minute < 10 ? ('0' + minute) : minute;
  second = second < 10 ? ('0' + second) : second;
  return Y + '-' + M + '-' + D + ' ' + h + ':' + minute + ':' + second;
}

//转换时间格式 （年月日）
function setTime5(timestr){
  var date = new Date(timestr * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
  var Y = date.getFullYear();
  var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
  var D = change(date.getDate());
  var h = change(date.getHours());
  var m = change(date.getMinutes());
  var s = change(date.getSeconds());
  return M + '-' + D+ ' ' + h + ':' + m + ':' + s;
}

function change(t) {
  if (t < 10) {
      return "0" + t;
  } else {
      return t;
  }
}

/**
 * 处理富文本里的图片宽度自适应
 * 1.去掉img标签里的style、width、height属性
 * 2.img标签添加style属性：max-width:100%;height:auto
 * 3.修改所有style里的width属性为max-width:100%
 * 4.去掉<br/>标签
 * @param html
 * @returns {void|string|*}
 */
function formatRichText(html){
  let newContent= html.replace(/<img[^>]*>/gi,function(match,capture){
    match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
    match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
    match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
    return match;
  });
  newContent = newContent.replace(/style="[^"]+"/gi,function(match,capture){
    match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
    return match;
  });
  newContent = newContent.replace(/<br[^>]*\/>/gi, '');
  newContent = newContent.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;margin-top:0;margin-bottom:0;"');
  return newContent;
}
function getWeek(date){
    var date = new Date(date);
    var weekdays = ['周日','周一','周二','周三','周四','周五','周六'];
    var day = date.getDay()
    var week = weekdays[day];
    return week
}

function getOrderStatus(status){
  let statusTxt = ''
  switch (status) {
    case '10':
      statusTxt = '全部'
      break;
    case '0':
      statusTxt = '待付款'
      break;
    case '1':
      statusTxt = '待发货'
      break;
    case '2':
      statusTxt = '待收货'
      break;
    case '3':
      statusTxt = '已完成'
      break;
    case '4':
      statusTxt = '已评价'
      break;
  }
  return statusTxt
}

const toChinesNum = (num) => {
  let changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']; //changeNum[0] = "零"
  let unit = ["", "十", "百", "千", "万"];
  num = parseInt(num);
  let getWan = (temp) => {
      let strArr = temp.toString().split("").reverse();
      let newNum = "";
      for (var i = 0; i < strArr.length; i++) {
          newNum = (i == 0 && strArr[i] == 0 ? "" : (i > 0 && strArr[i] == 0 && strArr[i - 1] == 0 ? "" : changeNum[strArr[i]] + (strArr[i] == 0 ? unit[0] : unit[i]))) + newNum;
      }
      return newNum;
  }
  let overWan = Math.floor(num / 10000);
  let noWan = num % 10000;
  if (noWan.toString().length < 4) noWan = "0" + noWan;
  return overWan ? getWan(overWan) + "万" + getWan(noWan) : getWan(num);

}


module.exports = {
    formatTime: formatTime,
    showModal: showModal,
    showToast: showToast,
    validation: validation,
    isEmojiCharacter: isEmojiCharacter,
    setNavBarColor:setNavBarColor,
    setNavBarTitle:setNavBarTitle,
    dateformat: dateformat,
    getAjax: getAjax,
    postAjax: postAjax,
    showModelAll:showModelAll,
    setTime: setTime,
    setTime2: setTime2,
    setTime3: setTime3,
    setTime4: setTime4,
    setTime5: setTime5,    
    formatRichText: formatRichText,
    getWeek:getWeek,
    getOrderStatus:getOrderStatus,
    toChinesNum:toChinesNum
}
